package com.ly.gen.service;

import cn.hutool.core.util.StrUtil;
import com.ly.gen.config.JdbcTemplateContext;
import com.ly.gen.model.TableInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MysqlTableService implements TableService {

    @Autowired
    private JdbcTemplateContext jdbcTemplateContext;

    /**
     * get table list
     *
     * @author leiyuan
     * @date 2023/2/19 0019
     **/
    @Override
    public List<TableInfo> getTableNames(Integer connId, String tableName) {
        String sql = "SELECT table_name, table_comment, create_time FROM information_schema.tables WHERE table_schema = (SELECT DATABASE()) ";
        if (StrUtil.isNotBlank(tableName)) {
            sql += " and table_name = :tableName";
        }
        sql += "ORDER BY create_time DESC";
        Map<String, Object> params = new HashMap<>();
        params.put("tableName", tableName);
        NamedParameterJdbcTemplate jdbcTemplate = jdbcTemplateContext.getJdbcTemplate(connId);
        return jdbcTemplate.query(sql, params, new TableInfoRowMapper());
    }

    class TableInfoRowMapper implements RowMapper<TableInfo>{

        @Override
        public TableInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
            TableInfo tableInfo = new TableInfo();
            tableInfo.setTableName(rs.getString(1));
            tableInfo.setTableComment(rs.getString(2));
            tableInfo.setCreateTime(rs.getString(3));
            return tableInfo;
        }
    }
}
